﻿using System;
using System.Xml;
using System.Xml.XPath;
using Sherwood.Content;
using Sherwood.Content.Contracts;
using Sherwood.Content.DO.Model;
using Sherwood.Content.UpdateServices;

namespace Sherwood.Samples.ArticleMeta
{
    public class ArticleMetaXmlUpdater : MetaUpdaterBase<ArticleMeta>
    {
        public ArticleMetaXmlUpdater(IMetaRepository metaRepository) : base(metaRepository)
        {
        }
        
        protected override void UpdateMeta(ArticleMeta meta, XmlReader reader)
        {
            var xpath = new XPathDocument(reader).CreateNavigator();

            var body = xpath.SelectSingleNode("*/body");
            meta.Body = body == null ? null : body.Value;

            var html = xpath.SelectSingleNode("*/html");
            meta.Html = html == null ? null : html.InnerXml;

            var author = xpath.SelectSingleNode("*/author");
            meta.Author = author == null ? null : author.InnerXml;

            var publishDate = xpath.SelectSingleNode("*/publishDate");
            meta.PublishDate = publishDate == null
                                   ? new DateTime?()
                                   : XmlConvert.ToDateTime(publishDate.InnerXml, XmlDateTimeSerializationMode.Utc);
        }
    }
}